package org.example.demo.controller;

import org.example.demo.model.CommonResponse;
import org.example.demo.model.bo.*;
import org.example.demo.raw.TeaAssetManagement;
import org.example.demo.service.TeaAssetManagementService;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Objects;

@RestController
@RequestMapping("/api/tea")
@CrossOrigin(origins = "*")
public class TeaAssetController {

    @Autowired
    private TeaAssetManagementService teaAssetManagementService;

    @PostMapping("/create")
    public CommonResponse createTeaAsset(@RequestBody TeaAssetManagementCreateTeaAssetInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.createTeaAsset(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @GetMapping("/details")
    public CommonResponse getTeaAssetDetails(@RequestParam String batchId) {
        try {
            TeaAssetManagementGetTeaAssetDetailsInputBO input = new TeaAssetManagementGetTeaAssetDetailsInputBO();
            input.set_batchId(parseId(batchId));
            CallResponse response = teaAssetManagementService.getTeaAssetDetails(input);
            
            // 创建自定义响应对象
            if (response != null && response.getReturnObject() != null) {
                // 将原始响应数据复制到新的Map中
                java.util.Map<String, Object> resultMap = new java.util.HashMap<>();
                resultMap.put("originData", response.getReturnObject());
                
                // 尝试获取状态码并添加状态描述
                try {
                    if (response.getReturnObject() instanceof java.util.List) {
                        java.util.List<?> returnList = (java.util.List<?>) response.getReturnObject();
                        if (returnList.size() >= 8 && returnList.get(7) instanceof java.math.BigInteger) {
                            java.math.BigInteger stageCode = (java.math.BigInteger) returnList.get(7);
                            resultMap.put("stageDesc", TeaAssetManagement.getAssetStageDesc(stageCode));
                        }
                    }
                } catch (Exception ex) {
                    // 解析错误，忽略状态描述
                    resultMap.put("stageDesc", "未知");
                }
                
                return CommonResponse.ok(resultMap);
            }
            
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @PostMapping("/update-processing")
    public CommonResponse updateProcessingInfo(@RequestBody TeaAssetManagementUpdateProcessingInfoInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.updateProcessingInfo(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @PostMapping("/submit-quality")
    public CommonResponse submitQualityReport(@RequestBody TeaAssetManagementSubmitQualityReportInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.submitQualityReport(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @PostMapping("/mark-sold")
    public CommonResponse markAsSold(@RequestBody TeaAssetManagementMarkAsSoldInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.markAsSold(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @PostMapping("/start-transporting")
    public CommonResponse startTransporting(@RequestBody TeaAssetManagementStartTransportingInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.startTransporting(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @PostMapping("/transfer-ownership")
    public CommonResponse transferOwnership(@RequestBody TeaAssetManagementTransferOwnershipInputBO input) {
        try {
            TransactionResponse response = teaAssetManagementService.transferOwnership(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }

    @GetMapping("/stage")
    public CommonResponse getAssetStage(@RequestParam String batchId) {
        try {
            TeaAssetManagementGetAssetStageInputBO input = new TeaAssetManagementGetAssetStageInputBO();
            input.set_batchId(parseId(batchId));
            CallResponse response = teaAssetManagementService.getAssetStage(input);
            return CommonResponse.ok(response);
        } catch (Exception e) {
            return CommonResponse.fail("1", e);
        }
    }
    
    // 解析批次ID（支持两种格式：十六进制字符串或Base64编码）
    private byte[] parseId(String id) {
        if (id == null || id.isEmpty()) {
            return new byte[0];
        }
        
        // 尝试按Base64解码
        try {
            return Base64.getDecoder().decode(id);
        } catch (IllegalArgumentException e) {
            // 不是有效的Base64，尝试按十六进制解析
            return hexStringToByteArray(id);
        }
    }
    
    // 工具方法：将十六进制字符串转换为字节数组
    private byte[] hexStringToByteArray(String hexString) {
        if (hexString == null || hexString.isEmpty()) {
            return new byte[0];
        }
        
        // 确保十六进制字符串的长度是偶数
        if (hexString.length() % 2 != 0) {
            hexString = "0" + hexString;
        }
        
        // 如果有0x前缀，去掉
        if (hexString.startsWith("0x")) {
            hexString = hexString.substring(2);
        }
        
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        
        return data;
    }
} 